const i18n = new VueI18n({
    locale: 'zh', // 设置默认
    messages
});


var em = new Vue({
    el: main,
    i18n,
    data: {
        options: [{//自动训练下拉框
            value: '7',
            label: '过去一周'
        }],
        value: '',//自动训练值
        optionstype: [{//预测模型类型
            value: '7',
            label: '随机森林（RF）'
        }],
        valuetype: '',//预测模型类型
        optionsday: [{//预测模型天数
            value: '7',
            label: '过去一周'
        }],
        ylsnd: [],
        xlsj: [],//数据模型列表
        cmx:[],//场模型列表
        valueday: '',//预测模型天数
        //传给模型的数据
        modeldata1:null,
        modeldata2:null,
        model1date:null,
        model2date:null,
        model1: false,
        model2: false,
        buttondisabled:true,
        leftNum: 0, //用来判断左侧菜单的样式，选取0位第一个
        menuLefts: [/*{ //构建的左侧菜单选项
            title: "homeMonitoring.Model_run",
            url: "../img/home/IconMonitoringS.png"
        }*/{ //构建的左侧菜单选项
            title: "数据模型",
            url: "../img/home/IconMonitoringS.png"
        },{ //构建的左侧菜单选项
            title: "场模型",
            url: "../img/home/iconHardware.png"
        }],
        //模型数据
        modelTableData: null, //表格数据
        dialogModerVisible: false,  //是否显示详情弹窗
        inputModerTableData: null,
        outputModerTableData: null,
        dialogModerVisibleYuRe: false, //执行预热弹窗
        formYuRe: {
            modelName: "",
        },
        YuReDate: null,
        OutputDate: null,
        fanweiFloseShow: true,       //默认都显示输入输出范围
        DingshiRadio: 0,         //按钮是否显示
        DingshiShow: false,
        outputShow:true,
        locals18n: "",
        form:{
            mxqssj:"",//模型计算起始时间
            num:0,//模拟天数
        },
        showsjmx: true,
        showcmx: false,
        tongjiX:[],
        tongjidata:[],
        legend:[],

    },
    created: function () {
        //初始化
        //获取训练列表
        console.log("开始")
        this.getxllb();
        this.getJosnModelData();
        try {
            window.parent.toggleLoading();
        } catch (e) {
        }
        this.locals18n = this.common.Initial();
        this.$i18n.locale = this.locals18n;
    },
    mounted(){
       this.getmap();
       //this.gettongji();
    },
    methods: {
        /**
         * 数据模型 模型训练按钮
         */
        mxxl(){
            var sj = {}
            sj.taskTime = "2025-01-03"
            sj.taskName = "测试"
            sj.type = '0'
            this.xlsj.push(sj)
        },
        /**
         * 获取训练列表
         */
        getxllb(){
            /**
             * 获取数据模型列表
             * @type {methods}
             */
            let that = this;
            this.$http.get('/task/getdata.do').then(function (res) {
                console.log(res.data);
                that.xlsj = res.data
            });
            /**
             * 获取场模型列表
             */
            this.$http.get('/task/getdatac.do').then(function (res) {
                console.log(res.data);
                that.cmx = res.data
            });
        },
        /**
         * 数据模型地图
         */
        getmap(){
            // 初始化地图，设置中心和缩放级别
            var map = L.map('mapid').setView([39,116], 10);
            var layer1 = L.tileLayer('http://t0.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=c238c2e699b3049118fc2fc693503707');
            var layer2 = L.tileLayer('http://t0.tianditu.gov.cn/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=c238c2e699b3049118fc2fc693503707');
            map.addLayer(layer1);
            map.addLayer(layer2);
        },
        /**
         * 场模型地图
         */
        getmapcmx(){
            // 初始化地图，设置中心和缩放级别
            var map = L.map('mapidcmx').setView([39,116], 10);
            var layer1 = L.tileLayer('http://t0.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=c238c2e699b3049118fc2fc693503707');
            var layer2 = L.tileLayer('http://t0.tianditu.gov.cn/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=c238c2e699b3049118fc2fc693503707');
            map.addLayer(layer1);
            map.addLayer(layer2);
        },
        /**
         * 查看按钮
         */
        deleteRow(index,data){
            console.log(data)
            that = this
            this.$http.get(('../hardware/getmoxingdata?id='+data[index].id+'&modelName=')).then(response => {
                console.log("sssssss")
                console.log(response)
                that.ylsnd = [];
                that.ylsnd= response.data;
                that.gettongji(data[index].id);
            })
                },
        /**
         * 时间格式化
         * @param row
         * @param column
         * @returns {string}
         */
            formatDate(row, column, cellValue, index) {
            const date = new Date(cellValue);
            const year = date.getFullYear();
            const month = ('0' + (date.getMonth() + 1)).slice(-2); // 月份是从0开始的
            const day = ('0' + date.getDate()).slice(-2);
            return `${year}-${month}-${day}`;
        },
        /**
         * 统计图
         */
        gettongji(id){
            that = this;
            this.$http.get(('../hardware/gettongji?id='+id)).then(response => {
                console.log("11111")
                console.log(response)
                if(response.data.length>0){//统计X轴日期
                    for (let i = 0; i <response.data[0].length; i++) {
                        that.tongjiX.push(that.timestampToDate(response.data[0][i].dataTime))
                    }
                    for (let i = 0; i <response.data.length ; i++) {//处理option 数据
                        var obj = {};
                        obj.name=response.data[i][0].modelName;
                        obj.type="line";
                        obj.stack="值";
                        var data = [];
                        that.legend.push(response.data[i][0].modelName)
                        for (let j = 0; j < response.data[i].length; j++) {
                            data.push(response.data[i][j].dataValue)
                        }
                        obj.data=data;
                        that.tongjidata.push(obj)
                    }
                    console.log(that.tongjidata)
                    var chartDom = document.getElementById('tongji');
                    var myChart = echarts.init(chartDom);
                    var option;
                    option = {
                        tooltip : {
                            trigger: 'axis'
                        },
                        legend: {
                            data:that.legend
                        },
                        toolbox: {
                            show : true,
                            feature : {
                                mark : {show: true},
                                dataView : {show: true, readOnly: false},
                                magicType : {show: true, type: ['line', 'bar', 'stack', 'tiled']},
                                restore : {show: true},
                                saveAsImage : {show: true}
                            }
                        },
                        calculable : true,
                        xAxis : [
                            {
                                type : 'category',
                                boundaryGap : false,
                                data :this.tongjiX
                            }
                        ],
                        yAxis : [
                            {
                                type : 'value'
                            }
                        ],
                        series : that.tongjidata
                    };
                    option && myChart.setOption(option);
                }
                
                

            })

        },
        //时间戳转换
        timestampToDate(timestamp) {
            const date = new Date(timestamp);
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的，所以需要+1，并确保是两位数
            const day = String(date.getDate()).padStart(2, '0'); // 日期，确保是两位数
            return `${year}-${month}-${day}`; // 返回格式为 YYYY-MM-DD
        },
        test() {
            return "?";
        },
        leftSwitch(index) { //上方菜单栏切换事件
            this.leftNum = index;
            console.log("菜单切换")
            for (i = 0; i < this.menuLefts.length; i++) {
                this.menuLefts[i].url = this.menuLefts[i].url.replace("S.png", ".png");
            }
            this.menuLefts[index].url = this.menuLefts[index].url.replace(".png", "S.png");
            switch (index) {
                case 0:
                    this.showsjmx=true;
                    this.showcmx = false;
                    that = this
                    setTimeout(function() {
                        // 这里是延迟执行的代码
                        that.getmap();
                    }, 1000);
                    break;
                case 1:
                    this.showsjmx=false;
                    this.showcmx = true;
                    that = this
                    setTimeout(function() {
                        // 这里是延迟执行的代码
                        that.getmapcmx();
                    }, 1000);
                    break;
                case 2:
                    break;
            }
        }, getJosnModelData() {
            this.$http.get('../Watershed/modelList.do', {emulateJSON: true}).then(function (res) {
                // console.log(res)
                this.modelTableData = res.data.list;
            });
        }, openModerDialog(type) {
            //弹窗
            this.dialogModerVisible = true;
            this.$http.get('../Watershed/detailed.do?type=' + type + '&operation=in', {emulateJSON: true}).then(function (res) {
                this.inputModerTableData = res.data.list;
            });
            this.$http.get('../Watershed/detailed.do?type=' + type + '&operation=out', {emulateJSON: true}).then(function (res) {
                this.outputModerTableData = res.data.list;
            });
        }, uploadSuccess(response, file, fileList) {
            if (response.code == 0) {
                //失败
                this.$message({
                    message: response.message,
                    type: 'warning'
                });
            } else {
                this.modeldata1 = response.message;
                var button = document.getElementById('buttondisabled');
                button.removeAttribute('disabled');
                // button.classList.add('el-button--default');
                // button.classList.remove('el-button--primary');
                button.classList.remove('is-disabled');
            }

        }, moderDownLoad(type, fileName) {

            this.$http.get('../Watershed/fileDown.do?type=' + type + '&fileName=' + fileName, {emulateJSON: true}).then(function (res) {
                if (res.data.code == 0) {
                    this.$message({
                        message: res.data.message,
                        type: 'error'
                    });
                } else {
                    window.location.href = '../Watershed/fileDown.do?type=' + type + '&fileName=' + fileName;
                }
            }).catch(function (result) {
                this.$message({
                    message: "暂无文件",
                    type: 'error'
                });
            });

        }, translation(row, column) {
            // console.log(row.modelName);
            //翻译模型 名称
            var name = row.modelName;
            return this.reallyTranslations(name);
        }, reallyTranslations(name) {
            if ("en" == this.locals18n) {
                switch (name) {
                    case "水流域":
                        name = messages.en.MonitoringTable.Water_basin;
                        break;
                    case "水动力":
                        name = messages.en.MonitoringTable.water_power;
                        break;
                    case "水质":
                        name = messages.en.MonitoringTable.Water_quality;
                        break;
                    case "手动串联":
                        name = messages.en.MonitoringTable.Manual_series;
                        break;
                    case "定时2点执行/天":
                        name = messages.en.MonitoringTable.Timeed_execution;
                        break;
                    case "水质模型":
                        name = messages.en.MonitoringTable.Water_quality_model;
                        break;
                    case "水流域模型":
                        name = messages.en.MonitoringTable.Watershed_model;
                        break;
                    case "水动力模型":
                        name = messages.en.MonitoringTable.Hydrodynamic_model;
                        break;
                     case "数据同化":
                        name = messages.en.MonitoringTable.Data_assimilation;
                        break;
                     case "读取一年his/test.his":
                    	 name = messages.en.MonitoringTable.Read_oneYeaHisr;
                    	 break;
                }
            }
            return name
        },
        dateFormatTime(row, column) {
            //表格上面格式化时间
            var date = row[column.property];
            if (date == null) {
                return new Date(parseInt(date)).toLocaleString().replace(/:\d{1,2}$/, ' ');
            }

            var dt = new Date(date);
            var year = dt.getFullYear();
            var month = dt.getMonth() + 1;
            var day = dt.getDate();
            var hour = dt.getHours();
            var minut = dt.getMinutes();
            var second = dt.getSeconds();
            month = month < 10 ? "0" + month : month;
            day = day < 10 ? "0" + day : day;
            hour = hour < 10 ? "0" + hour : hour;
            minut = minut < 10 ? "0" + minut : minut;
            second = second < 10 ? "0" + second : second;
            return year + "-" + month + "-" + day + " " + hour + ":" + minut + ":" + second;
        },
        doModer(data) {

            if (data.modelName == '数据模型') {
                this.model1 = true;
            } else {
                this.model1 = false;
            }
            if (data.modelName == '场模型') {
                this.model2 = true;
            } else {
                this.model2 = false;
            }

            //执行按钮
            // console.log(data);


            //知悉
            this.dialogModerVisibleYuRe = true;
            this.formYuRe = data;
            this.formYuRe.modelName = this.reallyTranslations(this.formYuRe.modelName)
            // this.$http.get('../Watershed/switch.do?type=' + type, {emulateJSON: true}).then(function (res) {
            //     this.$message({
            //         message: '已启动！',
            //         type: 'success'
            //     });
            // });


        },
        subYuRe() {
            var begindate1 = null;
            var enddate1 = null;
            if (this.model1date != null) {
                begindate1 = this.dateToString(this.model1date[0]);
                enddate1 = this.dateToString(this.model1date[1]);
            }

            var begindate2 = null;
            var enddate2 = null;
            if (this.model2date != null) {
                begindate2 = this.dateToString(this.model2date[0]);
                enddate2 = this.dateToString(this.model2date[1]);
            }
            window.parent.toggleLoading();
            layui.jquery.ajax({
                url: 'http://localhost:8088/Watershed/test.do',
                type: 'post',
                dataType: 'json',
                data: {
                    data: this.modeldata1,
                    startDate: begindate1,
                    endDate: enddate1
                },
                success: function (res){
                    console.log(res)
                    window.parent.toggleLoading();
                    this.dialogModerVisibleYuRe = false;
                    this.modeldata1 = null;
                    var button = document.getElementById('buttondisabled');
                    button.setAttribute('disabled',true);
                    button.classList.add('is-disabled');
                }
            })
/*
            this.$http.post('../Watershed/test.do?data=' + this.modeldata1 + "&startDate=" + begindate1 + "&endDate=" + enddate1, {emulateJSON: true}).then(function (res) {
                console.log(res)
                window.parent.toggleLoading();
                this.dialogModerVisibleYuRe = false;
            });
*/
        }, dateToString(date) {
            // 将data转化为String
            var year = date.getFullYear();
            var month = (date.getMonth() + 1).toString();
            var day = (date.getDate()).toString();
            if (month.length == 1) {
                month = "0" + month;
            }
            if (day.length == 1) {
                day = "0" + day;
            }
            var dateTime = year + "-" + month + "-" + day;
            return dateTime;
        }
    }
});